/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.store.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.javaeye.store.dao.MaterialsCategoryDAO;
import com.javaeye.store.dao.MaterialsDAO;
import com.javaeye.store.dto.MaterialsCategory;

public class MaterialsCategoryService implements IMaterialsCategoryService {
	
	private static Log log = LogFactory.getLog(MaterialsCategoryService.class);
	
	private MaterialsCategoryDAO dao;
	
	private MaterialsDAO meterialsDao;
	
	public void setDao(MaterialsCategoryDAO dao) {
		this.dao = dao;
	}

	public void setMeterialsDao(MaterialsDAO meterialsDao) {
		this.meterialsDao = meterialsDao;
	}

	@Override
	public MaterialsCategory getCategory(int id) {
		MaterialsCategory category = dao.getCategory(id);
		if (category == null) {
			log.warn("在数据库中未找到指定的物料分类  id：" + id);
		}
		return category;
	}

	@Override
	public List<MaterialsCategory> getCategorys(int parentId) {
		if (parentId < 0) {
			return new ArrayList<MaterialsCategory>();
		}
		List<MaterialsCategory> results = dao.getCategorys(parentId);
		if (results == null || results.size() == 0) {
			log.warn("在数据库中未找到物料分类数据");
		}
		return results;
	}
	
	//如果有子分类，则不能删除
	public boolean checkIsExitstChilds(int id) {
		long count = getCategorys(id).size();
		if (count > 0)
			return true;
		return false;
	}
	
	//判断物料表中是否使用
	public boolean checkIsUsedInMeterials(int id) {
		long count = meterialsDao.getCountByCategoryId(id);
		if (count > 0) 
			return true;
		return false;
	}

	@Override
	public boolean removeCategory(int id) {
		boolean isExitstChilds = checkIsExitstChilds(id);
		if (isExitstChilds) {
			return false;
		}
		boolean isUsed = checkIsUsedInMeterials(id);
		if (isUsed) {
			return false;
		}
		dao.removeCategory(id);
		return true;
	}

	@Override
	public MaterialsCategory saveCategory(MaterialsCategory category) {
		dao.saveCategory(category);
		return category;
	}
	
}
